package cn.itcast.demo.lock;

import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.scripting.support.ResourceScriptSource;

import java.util.Collections;
import java.util.UUID;

/**
 * @author 虎哥
 */
public class ReentrantRedisLock implements RedisLock{

    private final String key;
    private final StringRedisTemplate redisTemplate;

    public ReentrantRedisLock(String key, StringRedisTemplate redisTemplate) {
        this.key = key;
        this.redisTemplate = redisTemplate;
    }
    private final String VALUE_PREFIX = UUID.randomUUID().toString();
    /**
     * 获取锁的脚本
     */
    private static final DefaultRedisScript<Long> LOCK_SCRIPT;
    /**
     * 释放锁的脚本
     */
    private static final DefaultRedisScript<Object> UNLOCK_SCRIPT;
    static {
        // 加载获取锁的脚本
        LOCK_SCRIPT = new DefaultRedisScript<>();
        LOCK_SCRIPT.setScriptSource(new ResourceScriptSource(new ClassPathResource("lock.lua")));
        LOCK_SCRIPT.setResultType(Long.class);

        // 加载释放锁的脚本
        UNLOCK_SCRIPT = new DefaultRedisScript<>();
        UNLOCK_SCRIPT.setScriptSource(new ResourceScriptSource(new ClassPathResource("unlock.lua")));
    }

    private String releaseTime;

    @Override
    public boolean tryLock(long releaseTime) {
        this.releaseTime = String.valueOf(releaseTime);
        // 线程标示
        String value = VALUE_PREFIX + Thread.currentThread().getId();
        // 执行锁的脚本
        Long result = redisTemplate.execute(LOCK_SCRIPT,
                Collections.singletonList(key),
                value, this.releaseTime);
        // 判断结果
        return result != null && result.intValue() == 1;
    }

    @Override
    public void unlock() {
        // 线程标示
        String value = VALUE_PREFIX + Thread.currentThread().getId();
        // 执行脚本
        redisTemplate.execute(UNLOCK_SCRIPT, Collections.singletonList(key),value, this.releaseTime);
    }
}
